package com.yunmang.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.yunmang.R;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.OpenTicketResultBean;
import com.yunmang.entity.ParameterEntity.OpenTicketBean;
import com.yunmang.entity.event.EndEvent;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;
import com.yunmang.utils.FormatUtils;
import com.yunmang.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import HPRTAndroidSDK.HPRTPrinterHelper;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/6/19.
 */
public class FastOpenOrderActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.tv_delivery_station)
    TextView tvStrart;
    @InjectView(R.id.et_zd_station)
    TextView etZdStation;
    @InjectView(R.id.et_zz_station)
    EditText etZzStation;
    @InjectView(R.id.et_cargo_name)
    EditText etCargoName;
    @InjectView(R.id.spinner_pack)
    TextView spinnerPack;
    @InjectView(R.id.cargo_number)
    EditText cargoNumber;
    @InjectView(R.id.et_cargo_quality)
    EditText etCargoQuality;
    @InjectView(R.id.et_cargo_bulk)
    EditText etCargoBulk;
    @InjectView(R.id.et_date)
    TextView etDate;
    @InjectView(R.id.et_note_number)
    EditText etNoteNumber;
    @InjectView(R.id.save_noprint)
    Button btnSaveNoPrint;
    @InjectView(R.id.btn_save)
    Button btnSave;

    private int endId;
    private String[] packArray;
    private AlertView packAlertView;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static HPRTPrinterHelper HPRTPrinter = new HPRTPrinterHelper();
    private BluetoothAdapter myBluetoothAdapter;
    private boolean isTagprint = true, isReceiptPrint = true;//是否打印标签
    private String receipt_printer_style, tag_printer_style;//打印机类型
    private OpenTicketBean openTicketBean;
    private Subscriber subscriber;

    @Override
    public int getLayoutId() {
        return R.layout.activity_fastopen;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        initToolbar();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("打印标签");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        etDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
        tvStrart.setText(AppConstant.orgInfo.getName());
        etZdStation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context, SearchEndActivity.class));
            }
        });
        packArray = getResources().getStringArray(R.array.pack);
        spinnerPack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fillPack(packArray);
            }
        });
        cargoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                etNoteNumber.setText(charSequence.toString());
            }
            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @OnClick({R.id.et_zd_station, R.id.et_zz_station, R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_zd_station:
                break;
            case R.id.et_zz_station:
                break;
            case R.id.btn_save:
                showWaitingDialog("正在上传中……");
                btnSave.setEnabled(false);
                checkPageInfo(true);
                break;
        }
    }

    /**
     * 使用onEventMainThread来接收事件，那么不论分发事件在哪个线程运行，接收事件永远在UI线程执行
     * 可以用来更新UI
     *
     * @param event
     */
    public void onEventMainThread(EndEvent event) {
        endId = event.getId();
        etZdStation.setText(event.getName());
    }

    private void fillPack(String[] stringArray) {
        packAlertView = new AlertView(null, null, null, null, stringArray, this, AlertView.Style.Alert, this);
        packAlertView.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == packAlertView && position != AlertView.CANCELPOSITION) {
            spinnerPack.setText(packArray[position]);
        }
    }

    private void checkPageInfo(boolean b) {
        if (CommonUtils.checkTextIsEmpty(etZdStation)) {
            showToast("直达站不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etCargoName)) {
            showToast("货物名称不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(cargoNumber)) {
            showToast("货物数量不能为空！");
            onActionDone();
            return;
        }
        int UserId = Integer.parseInt(AppConstant.userid); // 用户ID
        int DepartId = AppConstant.orgInfo.getId(); // 起站ID
        int EndDepartId = endId;
        String TransferAddress = etZzStation.getText().toString().trim();
        String MemberNo = "";
        String GoodsName = CommonUtils.getTextViewValue(etCargoName);
        int Numbers = CommonUtils.ChangeString2Int(cargoNumber);
        String Pack = spinnerPack.getText().toString().trim();//包装
        int Cubage = CommonUtils.ChangeString2Int(etCargoBulk);//体积
        int Weight = CommonUtils.ChangeString2Int(etCargoQuality);//重量
        openTicketBean = new OpenTicketBean();
        openTicketBean.setHdbh("");
        openTicketBean.setUserId(UserId);
        openTicketBean.setDepartId(DepartId);
        openTicketBean.setEndDepartId(EndDepartId);
        openTicketBean.setTransferAddress(TransferAddress);
        openTicketBean.setMemberNo(MemberNo);
        openTicketBean.setShipperPhone("");
        openTicketBean.setShipper("");
        openTicketBean.setConsigneePhone("");
        openTicketBean.setConsignee("");
        openTicketBean.setConsigneeAddress("");
        openTicketBean.setTakeMethod("");
        OpenTicketBean.GoodsListEntity goodsListEntity = new OpenTicketBean.GoodsListEntity();
        goodsListEntity.setGoodsName(GoodsName);
        goodsListEntity.setNumbers(Numbers);
        goodsListEntity.setPack(Pack);
        goodsListEntity.setCubage(Cubage);
        goodsListEntity.setWeight(Weight);
        goodsListEntity.setPremiumAmount(0);
        List<OpenTicketBean.GoodsListEntity> list = new ArrayList<>();
        list.add(goodsListEntity);
        openTicketBean.setGoodsList(list);
        openTicketBean.setTransportCost(0);
        openTicketBean.setBalanceMethod(CommonUtils.getBalanceMethod("到付"));
        openTicketBean.setGoodsCost(0);
        openTicketBean.setTransferCost(0);
        openTicketBean.setDeliveryCost(0);
        openTicketBean.setTakeMethod("");
        openTicketBean.setDeliveryProofCount(0);
        openTicketBean.setNotes("");
        Gson gson = new Gson();
        String inJson = gson.toJson(openTicketBean);
        printKaipiao(inJson,true);
    }

    /**
     * true 表示要打出来票据
     * false 表示不出票只保存
     * @param b
     */
    private void printKaipiao(String inJson, boolean b) {
        if (b) {//需要对打印机类型做区分
            if (0 == SharedPreferencesUtils.getParameter(this, "SelectedTagMac").length()) {
                showToast("请选择标签打印机");
                onActionDone();
                return;
            }
            tag_printer_style = SharedPreferencesUtils.getParameter(context, "selectedTagName");
            receipt_printer_style = SharedPreferencesUtils.getParameter(context, "selectedPrintName");
            save(inJson);
        }
    }


    private void save(final String inJson) {
        subscriber = new Subscriber<OpenTicketResultBean>() {
            @Override
            public void onCompleted() {
                onActionDone();
            }

            @Override
            public void onError(Throwable e) {
                onActionDone();
                Log.i("LoginActivity", e.toString());
                Toast.makeText(context, "onError" + e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(final OpenTicketResultBean openTicketResultBean) {
                onActionDone();
                Log.e("data", inJson);
                if (openTicketResultBean.getCode() == 200) {
                    showAlertDialog("保存成功","不出标签，请在运单管理进行标签补打");
                    // TODO: 执行打印
                    if(tag_printer_style.equals(AppConstant.tag_name)){
                        actionTagByHanYin(openTicketResultBean.getModel());
                    }else{
                        showAlertDialog("保存成功","非汉印打印机,请检查");
                    }
                    deleteOrderInformation();
                } else if (openTicketResultBean.getCode() == 300) {
                    showToast(openTicketResultBean.getMessage());
                } else {
                    showToast("数据错误！");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), inJson);
        HttpUtils.getInstance().save(subscriber, body);
    }

    /**
     * 弹出对话框
     * @param string
     * */
    private void showAlertDialog(String hint,String string) {
        new AlertView(hint,string, null,new String[]{"确定"}, null,this,AlertView.Style.Alert,this).show();
    }

    /**
     * 删除开票信息
     */
    private void deleteOrderInformation() {
        etZzStation.setText("");
        etZdStation.setText("");
        etCargoName.setText("");
        cargoNumber.setText("");
        etCargoQuality.setText("");
        etCargoBulk.setText("");
        etNoteNumber.setText("");
    }

    private void actionTagByHanYin(final String model) {
        if(!HPRTPrinterHelper.IsOpened()){
            tryconnect(model);
        }else{
            PrintSampleReceipt(model);
        }
    }
    /**
     * 访问结束，需要置空
     */
    private void onActionDone() {
        hideWaitingDialog();
        btnSave.setEnabled(true);
        btnSaveNoPrint.setEnabled(true);
    }
    //打印机相关代码
    private void tryconnect(String model) {
        boolean hasConnected = false;
        hasConnected = ConnectDevice();
        if (hasConnected) {
            DisConnect();
        }
        if (hasConnected) {
            showToast("连接成功");
            this.HPRTPrinter = new HPRTPrinterHelper(this, "HM-T300");
            try {
                if (HPRTPrinterHelper.PortOpen("Bluetooth," + SharedPreferencesUtils.getParameter(this, "SelectedTagMac")) == 0) {
                    PrintSampleReceipt(model);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToast("连接失败");
        }
    }

    private void PrintSampleReceipt(String hdbh) {
        try {
            if (!HPRTPrinterHelper.IsOpened()) {
                showToast("请进行蓝牙连接");
                return;
            }
            int sumNum = Integer.parseInt(CommonUtils.getTextViewValue(cargoNumber));//总件数
            String tagnum = CommonUtils.getTextViewValue(etNoteNumber);
            if (!TextUtils.isEmpty(tagnum)) {
                sumNum = Integer.parseInt(tagnum);
                if (sumNum > 20) {
                    sumNum = 20;
                }
            }
            for (int i = 0; i < sumNum; i++) {
                HPRTPrinterHelper.printAreaSize("0", "200", "600", "450", "1");
                HPRTPrinterHelper.LanguageEncode = "GBK";
                HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
                HPRTPrinterHelper.Barcode(HPRTPrinterHelper.BARCODE, HPRTPrinterHelper.code128, "2", "1", "65", "40", "40", true, "7", "0", "5", hdbh + FormatUtils.generate(String.valueOf(i + 1)));
                HPRTPrinterHelper.Line("10", "135", "600", "135", "2");
                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "10", "150", CommonUtils.getTextViewValue(tvStrart) + "-" + CommonUtils.getTextViewValue(etZdStation));

                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "210", "货名:"+CommonUtils.getTextViewValue(etCargoName)+"  件数:"+CommonUtils.getTextViewValue(cargoNumber));
                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "280", "包装:"+CommonUtils.getTextViewValue(spinnerPack));
                HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "350", DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                HPRTPrinterHelper.Form();
                HPRTPrinterHelper.PrintData("POPRINT\r\n");
            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
        }
    }

    private boolean ConnectDevice() {
        boolean bRet = false;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myBluetoothAdapter.cancelDiscovery();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            // 4.0.3版本 经测试，高版本兼容低版本
            mmDevice = myBluetoothAdapter.getRemoteDevice(SharedPreferencesUtils.getParameter(context, "SelectedTagMac"));
            if (Build.VERSION.SDK_INT < 15) {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } else {
                mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            }
            myBluetoothAdapter.cancelDiscovery();
            Thread.sleep(100);
            if (myBluetoothAdapter.isDiscovering()) {
                int iCnt = 0;
                while (iCnt < 5) {
                    Thread.sleep(100);
                    iCnt++;
                    if (myBluetoothAdapter.cancelDiscovery()) {
                        break;
                    }
                }
            }
            mmSocket.connect();
        } catch (Exception e) {
            try {
                Method m;
                m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
                if (myBluetoothAdapter.isDiscovering()) {
                    int iCnt = 0;
                    while (iCnt < 5) {
                        Thread.sleep(100);
                        iCnt++;
                        if (myBluetoothAdapter.cancelDiscovery()) {
                            break;
                        }
                    }
                }
                mmSocket.connect();
            } catch (Exception e1) {
                Log.d("PRTLIB", (new StringBuilder("BTO_ConnectDevice --> create ")).append(e1.getMessage()).toString());
                return false;
            }
        }

        try {
            bRet = GetIOInterface();
            return bRet;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean GetIOInterface() {
        Log.d("PRTLIB", "BTO_GetIOInterface...");
        try {
            mmInStream = mmSocket.getInputStream();
            mmOutStream = mmSocket.getOutputStream();
        } catch (IOException e) {
            Log.d("PRTLIB", (new StringBuilder("BTO_GetIOInterface ")).append(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothDevice mmDevice;
    private BluetoothSocket mmSocket;

    private boolean DisConnect() {
        boolean bRet = true;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mmInStream != null) {
                mmInStream.close();
                mmInStream = null;
            }
            if (mmOutStream != null) {
                mmOutStream.close();
                mmOutStream = null;
            }
            if (mmSocket != null) {
                mmSocket.close();
                mmSocket = null;
            }
        } catch (IOException e) {
            System.out.println((new StringBuilder("BTO_ConnectDevice close ")).append(e.getMessage()).toString());
            bRet = false;
        }
        return bRet;
    }

}
